
from PyQt5.QtGui import QColor, QFont
from qgis._core import QgsFillSymbol, QgsLineSymbol, QgsMarkerSymbol, \
    QgsSingleSymbolRenderer, QgsPalLayerSettings, QgsTextFormat, QgsTextBufferSettings, QgsWkbTypes, \
    QgsVectorLayerSimpleLabeling
from demo.layer_config import LAYER_STYLES


def apply_fixed_style(layer):
    # 使用预定义配置
    lname = layer.name().upper()
    print(f"应用样式到图层: {lname}")

    # 获取预定义样式配置
    style_config = LAYER_STYLES.get(lname)

    if not style_config:
        print(f"无预定义样式: {lname}")
        return

    # 根据图层类型应用不同样式
    try:
        if style_config["type"] == "fill":
            symbol = QgsFillSymbol.createSimple({
                'color': style_config["color"],
                'outline': style_config["outline"],
                'outline_width': style_config["width"]
            })
        elif style_config["type"] == "line":
            symbol = QgsLineSymbol.createSimple({
                'color': style_config["color"],
                'width': style_config["width"],
                'style': style_config.get("style", "solid")
            })
        elif style_config["type"] == "marker":
            symbol = QgsMarkerSymbol.createSimple({
                'color': style_config["color"],
                'size': style_config["size"],
                'name': style_config["shape"],
                'outline': style_config.get("outline", "black")
            })

        layer.setRenderer(QgsSingleSymbolRenderer(symbol))
        print(f"{lname}图层样式已应用: {style_config}")

        # 为等深线添加标签
        if lname == "DEPCNT":
            apply_label(layer, "VALDCO")

    except Exception as e:
        print(f"样式应用失败: {lname} - {str(e)}")

    # 刷新图层
    layer.triggerRepaint()

def apply_label(layer, field_name):
    # 为图层添加标签
    if field_name not in [f.name() for f in layer.fields()]:
        return

    settings = QgsPalLayerSettings()
    settings.fieldName = field_name
    settings.enabled = True

    # 文本格式
    format = QgsTextFormat()
    format.setSize(8)
    format.setColor(QColor("black"))

    font = QFont("Arial", 8)
    format.setFont(font)

    # 文本缓冲
    buffer_settings = QgsTextBufferSettings()
    buffer_settings.setEnabled(True)
    buffer_settings.setSize(0.5)
    buffer_settings.setColor(QColor("white"))
    format.setBuffer(buffer_settings)

    settings.setFormat(format)

    # 标签位置
    if layer.geometryType() == QgsWkbTypes.PointGeometry:
        settings.placement = QgsPalLayerSettings.AroundPoint
    elif layer.geometryType() == QgsWkbTypes.LineGeometry:
        settings.placement = QgsPalLayerSettings.Curved
    else:
        settings.placement = QgsPalLayerSettings.OverPoint

    labeling = QgsVectorLayerSimpleLabeling(settings)
    layer.setLabeling(labeling)
    layer.setLabelsEnabled(True)
    layer.triggerRepaint()